package _6_13;

public class HexUtils {

    // 数字 → 十六进制字符映射
    private static final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();

    /** 字符串转 16 进制字符串（不使用 Java 内置 API） */
    public static String strToHex(String str) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            int ch = (int) str.charAt(i);  // 获取字符的 ASCII 值
            // 拆成高4位和低4位
            char high = HEX_CHARS[(ch >> 4) & 0xF];
            char low  = HEX_CHARS[ch & 0xF];
            sb.append(high).append(low);
        }
        return sb.toString();
    }

    /** 16 进制字符串 → 原始字符串（不使用 Java 内置 API） */
    public static String hexToStr(String hex) {
        if (hex.length() % 2 != 0) {
            throw new IllegalArgumentException("hex length must be even.");
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hex.length(); i += 2) {
            // 取两个字符，还原成一个字节值
            int high = hexCharToInt(hex.charAt(i));
            int low  = hexCharToInt(hex.charAt(i + 1));
            int ch = (high << 4) | low;
            sb.append((char) ch);
        }
        return sb.toString();
    }

    /** 单个十六进制字符转整数（'0'→0, 'A'→10, 'f'→15） */
    private static int hexCharToInt(char c) {
        if (c >= '0' && c <= '9') return c - '0';
        else if (c >= 'A' && c <= 'F') return c - 'A' + 10;
        else if (c >= 'a' && c <= 'f') return c - 'a' + 10;
        else throw new IllegalArgumentException("Invalid hex char: " + c);
    }

    public static void main(String[] args) {
        String original = "Hello世界!";
        String hex = strToHex(original);
        String decoded = hexToStr(hex);

        System.out.println("原始字符串: " + original);
        System.out.println("转为16进制: " + hex);
        System.out.println("还原字符串: " + decoded);
    }
}
